import os
from alibabacloud_dysmsapi20170525.client import Client as DysmsapiClient  # noqa
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_models  # noqa
from alibabacloud_tea_util import models as util_models

from configs import ALIBABA_CLOUD_ACCESS_KEY_SECRET, ALIBABA_CLOUD_ACCESS_KEY_ID, ALIYUN_SMS_TEMPLATE_CODE, ALIYUN_SMS_SIGN_NAME


class AliyunSMS:
    def __init__(self):
        self.client = self.create_client()
        # 从环境变量获取配置（需提前设置）
        self.sign_name = ALIYUN_SMS_SIGN_NAME
        self.template_code = ALIYUN_SMS_TEMPLATE_CODE

    @staticmethod
    def create_client() -> DysmsapiClient:
        config = open_api_models.Config(
            access_key_id=ALIBABA_CLOUD_ACCESS_KEY_ID,
            access_key_secret=ALIBABA_CLOUD_ACCESS_KEY_SECRET
        )
        config.endpoint = 'dysmsapi.aliyuncs.com'
        return DysmsapiClient(config)

    def send_sms(self, phone: str, code: str):
        """发送短信验证码"""
        req = dysmsapi_models.SendSmsRequest(
            phone_numbers=phone,
            sign_name=self.sign_name,
            template_code=self.template_code,
            template_param=f'{{"code":"{code}"}}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            resp = self.client.send_sms_with_options(req, runtime)
            if resp.body.code != 'OK':
                raise Exception(f'阿里云短信错误: {resp.body.message}')
            return True
        except Exception as e:
            print(f'短信发送失败: {str(e)}')
            return False


SMS_CLIENT = AliyunSMS()  # 实例化短信客户端
